package com.ysq.www.api.front.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ysq.www.api.front.entity.Activity;
import com.ysq.www.api.front.mapper.ActivityApplyMapper;
import com.ysq.www.api.front.mapper.ActivityMapper;
import com.ysq.www.api.front.service.IActivityService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ysq.www.api.user.entity.Collect;
import com.ysq.www.api.user.entity.User;
import com.ysq.www.api.user.mapper.CollectMapper;
import com.ysq.www.api.user.mapper.UserMapper;
import com.ysq.www.api.work.entity.Approve;
import com.ysq.www.api.work.entity.CopyTo;
import com.ysq.www.api.work.mapper.ApproveMapper;
import com.ysq.www.api.work.mapper.CopyToMapper;
import com.ysq.www.common.result.ResultMsg;
import com.ysq.www.common.utils.Comm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 活动表 服务实现类
 * </p>
 *
 * @author dql
 * @since 2020-08-08
 */
@Service
public class ActivityServiceImpl extends ServiceImpl<ActivityMapper, Activity> implements IActivityService {

    @Autowired
    private ActivityMapper activityMapper;

    @Autowired
    private ActivityApplyMapper activityApplyMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CopyToMapper copyToMapper;

    @Autowired
    private ApproveMapper approveMapper;

    @Autowired
    private CollectMapper collectMapper;

    /**
     * 首页分页查询最新活动
     * @param pageSize 页大小
     * @param pageNumber 页码
     * @param asId 协会id
     * @return ResultMsg
     */
    @Override
    public ResultMsg selectByPage(Integer pageSize, Integer pageNumber, Integer asId){
        QueryWrapper<Activity> wrapper = new QueryWrapper<>();
        wrapper.select("id","pc_url","name","price","start_time","end_time","as_id").eq("check_status",2)
                .eq("status",0).eq("as_id",asId).orderByDesc("create_time");
        Page<Activity> page = new Page<>(pageNumber,pageSize);
        IPage<Activity> iPage = activityMapper.selectPage(page, wrapper);
        List<Activity> records = iPage.getRecords();
        for (Activity record : records) {
            int a = record.getEndTime().compareTo(new Date());
            if (a > 0){
                record.setPastDue(0);//已过期
            }else record.setPastDue(1);//未过期
            Integer amount = activityApplyMapper.selectAmountById(record.getId());//查询已报名人数
            record.setAmount(amount);
        }
        iPage.setRecords(records);
        return ResultMsg.SUCCESS.setNewMsg("分页查询成功").setNewData(iPage);
    }

    /**
     * 查询活动详情
     * @param apId 活动id
     * @param userId 用户id
     * @return Activity
     */
    @Override
    public Activity selectDetailById(Integer apId, Integer userId) {
        Activity at = activityMapper.selectDetailById(apId);
        String copyIds = at.getCopyId();
        if (StringUtils.isEmpty(copyIds)) return at;
        String[] cps = copyIds.split(";");
        List<Integer> idList = new ArrayList<>();
        for (String c : cps) {
            idList.add(Integer.parseInt(c));
        }
        List<User> userList = userMapper.selectBatchIds(idList);
        at.setCopyList(userList);
        int a = at.getEndTime().compareTo(new Date());
        if (a > 0){
            at.setPastDue(0);//已过期
        }else at.setPastDue(1);//未过期
        Integer amount = activityApplyMapper.selectAmountById(at.getId());//查询已报名人数
        at.setAmount(amount);
        if (userId != null && userId != 0){
            Collect ct = collectMapper.selectCollectById(at.getId(),userId,2);
            if (ct != null) at.setIsCollect(1);//已收藏
            else at.setIsCollect(0);//未收藏
        }else at.setIsCollect(0);
        return at;
    }

    /**
     * 提交活动
     * @param at 活动实体对象
     * @return ResultMsg
     */
    @Override
    @Transactional
    public ResultMsg addActivity(Activity at) {
        at.setCreateTime(Comm.getNow());
        at.setCheckStatus(0);
        at.setStatus(0);
        boolean save = this.save(at);
        if (save){//创建审批记录
            Approve app = new Approve();
            app.setType(7);//类型:活动
            app.setContentId(at.getId());
            app.setCheckId(at.getApproverId());
            app.setSupperId(0);
            app.setLowerId(0);
            app.setCheckTime(Comm.getNow());
            app.setCheckStatus(0);
            app.setCreateTime(Comm.getNow());
            app.setStatus(0);
            approveMapper.insert(app);

            //创建抄送记录
            String copyIds = at.getCopyId();
            if (!StringUtils.isEmpty(copyIds)){
                List<CopyTo> cList = new ArrayList<>();
                String[] copyId = copyIds.split(";");
                for (String c : copyId) {
                    CopyTo ct = new CopyTo();
                    ct.setType(6);//活动
                    ct.setContentId(at.getId());//内容id
                    ct.setUserId(Integer.parseInt(c));//抄送至用户的id
                    ct.setCreateTime(Comm.getNow());//创建时间
                    ct.setStatus(0);
                    cList.add(ct);
                }
                if (cList.size() > 0){
                    //copyToMapper.insertList(cList);
                    copyToMapper.insertListByNote(cList);
                }
            }
            return ResultMsg.INSERT_SUCCESS.setNewMsg("提交成功");
        }else return ResultMsg.UPDATE_ERROR.setNewMsg("提交失败,内部错误");
    }

    /**
     * 待办分页查询我发起的活动
     * @param userId 发起人id
     * @param pageNumber 页码
     * @param pageSize 页大小
     * @param time 日期
     * @return IPage
     */
    @Override
    public IPage<Activity> selectSponsorByPage(Integer userId, Integer pageNumber, Integer pageSize, String time) {
        QueryWrapper<Activity> wrapper = new QueryWrapper<>();
        wrapper.eq("status",0).eq("user_id",userId);
        if (!StringUtils.isEmpty(time)){
            String startTime = time + " 00:00:00";
            String endTime = time + " 23:59:59";
            wrapper.between("create_time",startTime,endTime);
        }
        wrapper.orderByDesc("create_time");
        Page<Activity> page = new Page<>(pageNumber,pageSize);
        return activityMapper.selectPage(page,wrapper);
    }

    /**
     * 分页查询待处理/已处理活动
     * @param userId 审批人id
     * @param type 类型：0未处理，1已处理
     * @param pageNumber 页码
     * @param pageSize 页大小
     * @param time 日期
     * @return IPage
     */
    @Override
    public IPage<Activity> selectPendingByPage(Integer userId, Integer type, Integer pageNumber, Integer pageSize, String time) {
        QueryWrapper<Activity> wrapper = new QueryWrapper<>();
        wrapper.eq("status",0).eq("approver_id",userId);
        if (type == 0) wrapper.eq("check_status",0);
        else if (type == 1){
            wrapper.ne("check_status",0).ne("check_status",3);
            if (!StringUtils.isEmpty(time)){
                String startTime = time + " 00:00:00";
                String endTime = time + " 23:59:59";
                wrapper.between("create_time",startTime,endTime);
            }
        }
        wrapper.orderByDesc("create_time");
        Page<Activity> page = new Page<>(pageNumber,pageSize);
        return activityMapper.selectPage(page,wrapper);
    }

    /**
     * 分页查询抄送至我的活动
     * @param userId 用户id
     * @param pageNumber 页码
     * @param pageSize 页大小
     * @param time 日期
     * @return IPage
     */
    @Override
    public IPage<Activity> selectCopyToMeByPage(Integer userId, Integer pageNumber, Integer pageSize, String time) {
        QueryWrapper<CopyTo> cWrapper = new QueryWrapper<>();
        cWrapper.eq("status",0).eq("user_id",userId).eq("type",6);
        List<CopyTo> cList = copyToMapper.selectList(cWrapper);
        if (cList.isEmpty()) return null;
        List<Integer> idList = new ArrayList<>();
        for (CopyTo c : cList) {
            idList.add(c.getContentId());
        }
        QueryWrapper<Activity> wrapper = new QueryWrapper<>();
        wrapper.eq("status",0).ne("check_status",3).in("id",idList);
        if (!StringUtils.isEmpty(time)){
            String startTime = time + " 00:00:00";
            String endTime = time + " 23:59:59";
            wrapper.between("create_time",startTime,endTime);
        }
        wrapper.orderByDesc("create_time");
        Page<Activity> page = new Page<>(pageNumber,pageSize);
        return activityMapper.selectPage(page,wrapper);
    }

    /**
     * 审批处理提交的活动
     * @param atId 活动id
     * @param result 处理结果：1通过，2驳回
     * @return ResultMsg
     */
    @Override
    @Transactional
    public ResultMsg checkActivityById(Integer atId, Integer result) {
        Activity at = activityMapper.selectById(atId);
        if (at.getCheckStatus() != 0) return ResultMsg.UPDATE_ERROR.setNewMsg("处理失败，活动已处理或已撤销");
        at.setCheckStatus(result);
        at.setUpdateTime(Comm.getNow());
        this.updateById(at);
        UpdateWrapper<Approve> wrapper = new UpdateWrapper<>();
        wrapper.set("check_time",Comm.getNow()).set("check_status",result).set("update_time",Comm.getNow()).
                eq("type",7).eq("content_id",atId);
        approveMapper.update(null,wrapper);
        //activityMapper.checkActivityById(atId,result);
        return ResultMsg.UPDATE_SUCCESS.setNewMsg("处理成功");
    }

    /**
     * 撤销提出但还未处理的活动
     * @param atId 活动id
     * @return ResultMsg
     */
    @Override
    @Transactional
    public ResultMsg repealActivityById(Integer atId) {
        Activity at = activityMapper.selectById(atId);
        if (at.getCheckStatus() != 0) return ResultMsg.UPDATE_ERROR.setNewMsg("撤销失败，该活动已处理不能撤销");
        at.setCheckStatus(3);
        at.setUpdateTime(Comm.getNow());
        activityMapper.updateById(at);
        UpdateWrapper<Approve> wrapper = new UpdateWrapper<>();
        wrapper.set("check_time",Comm.getNow()).set("check_status",3).set("update_time",Comm.getNow()).
                eq("type",7).eq("content_id",atId);
        approveMapper.update(null,wrapper);
        return ResultMsg.UPDATE_SUCCESS.setNewMsg("撤销成功");
    }


}
